package fhq.hcmute.edu.vn.camera;

import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import fhq.hcmute.edu.vn.util.ProjectUtil;

/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements
		SurfaceHolder.Callback {
	private SurfaceHolder mHolder;
	private Camera mCamera;
	private PreviewCallback previewCallback;
	private AutoFocusCallback autoFocusCallback;
	private Activity activity;

	@SuppressWarnings("deprecation")
	public CameraPreview(Activity activity, Camera camera,
			PreviewCallback previewCb, AutoFocusCallback autoFocusCb) {
		super(activity);
		mCamera = camera;
		previewCallback = previewCb;
		autoFocusCallback = autoFocusCb;
		this.activity = activity;
		mHolder = getHolder();
		mHolder.addCallback(this);

		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	public final void surfaceCreated(final SurfaceHolder holder) {
		try {
			mCamera.setPreviewDisplay(holder);
		} catch (IOException e) {
			Log.d("DBG", "Error setting camera preview: " + e.getMessage());
		}
	}

	public void surfaceDestroyed(final SurfaceHolder holder) {
		// Camera preview released in activity
	}

	public final void surfaceChanged(final SurfaceHolder holder,
			final int format, final int width, final int height) {
		/*
		 * If your preview can change or rotate, take care of those events here.
		 * Make sure to stop the preview before resizing or reformatting it.
		 */
		if (mHolder.getSurface() == null) {
			// preview surface does not exist
			return;
		}

		// stop preview before making changes
		try {
			mCamera.stopPreview();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			// Hard code camera surface rotation 90 degs to match Activity view
			// in portrait
			// mCamera.setDisplayOrientation(90);
			int rotation = activity.getWindowManager()
					.getDefaultDisplay().getRotation();
			int degrees = 0;
			switch (rotation) {
			case Surface.ROTATION_0:
				degrees = ProjectUtil.SCREEN_VERTICAL_UP;
				break;
			case Surface.ROTATION_90:
				degrees = ProjectUtil.SCREEN_HORIZONTAL_LEFT;
				break;
			case Surface.ROTATION_180:
				degrees = ProjectUtil.SCREEN_HORIZONTAL_RIGHT;
				break;
			default:
				degrees = ProjectUtil.SCREEN_VERTICAL_DOWN;
				break;
			}
			mCamera.setDisplayOrientation(degrees);
			mCamera.setPreviewDisplay(mHolder);
			mCamera.setPreviewCallback(previewCallback);
			mCamera.startPreview();
			mCamera.autoFocus(autoFocusCallback);
		} catch (Exception e) {
			Log.d("DBG", "Error starting camera preview: " + e.getMessage());
		}
	}
}
